package com.huang.wangpan.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * @author: liminghui
 * @date: 2020/11/7 23:12
 * @version: 1.0
 * @description:
 */
public class GetLocalIpsUtil {

    private static final Logger logger = LoggerFactory.getLogger(GetLocalIpsUtil.class);

    public static String getLocalIps() {

        //get all local ips
        Enumeration<NetworkInterface> interfs = null;
        try {
            interfs = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            logger.error("GetLocalIpsUtil-->getLocalIps accur error!!", e);
        }
        String hostAddress = null;
        w1:
        while (interfs.hasMoreElements()) {
            NetworkInterface interf = interfs.nextElement();
            Enumeration<InetAddress> addres = interf.getInetAddresses();
            while (addres.hasMoreElements()) {
                InetAddress in = addres.nextElement();
                if (in instanceof Inet6Address) {
                    hostAddress = in.getHostAddress();
                    if (hostAddress.startsWith("2409:8a56:33e3:a070")) {
                        logger.info("ipv6:{}", hostAddress);
                        break w1;
                    }
                }
            }


        }
        return hostAddress;
    }

}
